const express = require('express')
const { queryGoodsInfoByGoodsId } = require('../mysql/goodsInfo')
const { queryAllImageByGoodsId } = require('../mysql/image')
const Result = require('../result/result')
const { NO_PERMISSION } = require('../result/reponseState')

const router = express.Router()

router.get('', async (req, res) => {
  const { goods_id } = req.query
  try {
    const base = ['goods_id', 'goods_name', 'goods_desc']
    const result = await queryGoodsInfoByGoodsId(goods_id)
    const keys = Object.keys(result[0]).filter((key) => base.includes(key) === false)
    const baseObj = {}
    const msgArr = []
    result.forEach((e, index) => {
      const msgObj = {}
      msgObj.others = []
      const other = {}
      for (const key in e) {
        if (base.includes(key)) {
          baseObj[key] = e[key]
        } else if (keys.includes(key)) {
          if (e.goods_version) {
            if (key === 'goods_version') {
              msgObj[key] = e[key]
            } else {
              other[key] = e[key]
            }
          }
        }
      }
      if (msgArr.length > 0) {
        let flag = true
        let eindex
        for (let i = 0; i < msgArr.length; i++) {
          const e = msgArr[i]
          eindex = i
          if (e.goods_version == msgObj.goods_version) {
            flag = true
            break
          } else {
            flag = false
          }
        }
        if (flag) {
          msgArr[eindex].others.push(other)
        } else {
          msgObj.others.push(other)
          msgArr.push(msgObj)
        }
      } else {
        msgObj.others.push(other)
        msgArr.push(msgObj)
      }
    })
    const obj = {
      ...baseObj,
      msg: msgArr
    }
    res.send(Result.ok(obj))
  } catch (error) {
    res.send(Result.error2(NO_PERMISSION, error))
  }
})
router.get('/image', (req, res) => {
  const { goods_id } = req.query
  queryAllImageByGoodsId(goods_id).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})
module.exports = router